package com.point.ootb.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.point.ootb.core.ServiceException;
import com.point.ootb.domain.dto.LoginDTO;
import com.point.ootb.domain.dto.RegisterDTO;
import com.point.ootb.domain.enity.SysUser;
import com.point.ootb.domain.vo.LoginUserInfoVO;
import com.point.ootb.mapper.SysUserMapper;
import com.point.ootb.service.ILoginService;
import com.point.ootb.util.LoginInfoUtil;
import com.point.ootb.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@RequiredArgsConstructor
public class LoginServiceImpl extends ServiceImpl<SysUserMapper, SysUser>  implements ILoginService {


    @Override
    public String login(LoginDTO loginDTO) {
        SysUser sysUser = baseMapper.selectOne(new LambdaQueryWrapper<>(SysUser.class)
                .eq(SysUser::getPhone , loginDTO.getPhone())
                .select(SysUser::getId, SysUser::getPhone, SysUser::getPassword));
        if(Objects.isNull(sysUser)){
            throw new ServiceException("手机号不存在 ， 请先注册");
        }
        boolean pass = SecurityUtils.matchesPassword(loginDTO.getPassword(), sysUser.getPassword());
        if(!pass){
            throw new ServiceException("密码错误 ，请重试");
        }
        LoginInfoUtil.login(sysUser.getLoginUserInfo(sysUser));
        return StpUtil.getTokenValue();
    }

    @Override
    public void register(RegisterDTO registerDTO) {
        boolean exists = baseMapper.exists(new LambdaQueryWrapper<>(SysUser.class)
                .eq(SysUser::getPhone, registerDTO.getPhone()));
        if(exists){
            throw new ServiceException("手机号已存在");
        }
        SysUser user = SysUser.builder()
                .phone(registerDTO.getPhone())
                .nickName(registerDTO.getNickName())
                .password(SecurityUtils.encryptPassword(registerDTO.getPassword())).build();
        baseMapper.insert(user);
    }

    @Override
    public LoginUserInfoVO getLoginUserInfo() {
        return LoginInfoUtil.getLoginUser();
    }

}
